<?php
/**
 * @filesource modules/news/controllers/IndexController.php
 * @author Dao Quang Duc
 * @abstract : List of actions in order
 *   - new
 *   - view
 *   - edit
 *   - delete
 *   - search
 */ 
class News_IndexController extends Clu_Controller_Action_Hvn
{
	public $m,$c;//, $mPlace, $mArticle;
	
	public function init()
	{
		//require_once (APP_PATH.'/modules/category/Model/Category.php');
		//require_once (APP_PATH.'/modules/article/Model/Article.php');
		//require_once (APP_PATH.'/modules/user/Model/User.php');
		$this->mArticle = new article_Model_Service();
		$this->m = new Model_News();
		$this->c = new category_Model_Category();
		
		parent::init();
		
	}
	
	public function newAction() 
	{
	 //check user permissions here
        $sess = new Zend_Session_Namespace(CLU_NS);
        if (strpos ($sess->userPermissions, 'create news') === false)
        {
            $this->view->errorMessage .= t(68);
            $this->renderToHolder( 'common/error.phtml');
            return;
        }
        
		$this->view->form = new Form_News();
        $this->view->form->cluBuild(array ('action' => 'new', 'view' => $this->view, 'userPermissions' => $sess->userPermissions));
     	$this->view->mode = "new";
        if ($this->_request->isPost() && $this->view->form->isValid($_POST)) 
        {
        	$data = $this->_request->getParams();
        	$db = $this->db;
	        $db->beginTransaction();
            try 
            {
            	$data['article_title'] 		= $data['title'];
            	$data['article_body']  		= $data['body'];
            	$data['article_language'] 	= $data['newsLanguage'];
            	$data['article_module'] 	= "news";
            	$data['article_keywords'] 	= $data['keywords'];
                if (!$this->mArticle->insertRaw($data,false))
                {
                	$this->view->errorMessage .= t(304);
                }
                $article_id = $db->lastInsertId();
            	$data['article_id'] = $article_id;
                
    			if($article_id != 0)
                {
		            try
			    	{
			    	   	$newsId = $this->m->insertRaw($data,false);
			    	}
			    	catch (Exception $e) 
			    	{
			    		$this->mArticle->deleteByPrimary(array($article_id, false));
			    	    $this->view->errorMessage .= t(304);
			    	}
                }
                 $db->commit();
            }
             catch (Exception $e)
            {
                $db->rollBack();
                 $this->view->errorMessage .= "<br/" . t(69);
            }
			 $this->_forward("success", 'index' , 'news', array('lastInsertId' => $article_id, 'lang' => 'en' ) );
        	return;
        }
		else if ($this->_request->isPost() )
        {
        	$this->view->errorMessage .= t(1);
        }
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
        $this->renderToHolder('index/new.phtml', false, null, 4,1); 
	}
	
	public function viewAction() 
	{
		$id = $this->_request->getParam("id");
    	if (!$n = $this->m->findByPrimary($id))
        {
            $this->view->errorMessage .= t(305);
            $this->renderToHolder('common/error.phtml');
            return;
        }
        
		$sess = new Zend_Session_Namespace(CLU_NS);
        if (strpos ($sess->userPermissions, 'read news') === false)
        {
            $this->view->errorMessage .= t(70);
            $this->renderToHolder( 'common/error.phtml');
            return;
        }

        $this->view->news = $this->m->transformToFormArray($n,false);
        $this->renderToHolder('index/view.phtml', false, null, 4, 1);
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest); 
        
        //TODO: add comment section here
        $this->_helper->actionStack('view',
                                    'index',
                                    'comment',
                                    array('lang' => Zend_Registry::get('viewLang'),
                                          'parent_content_type' => 'news',
                                          'parent_content_id'   => $id,
                                          'hvnBoxWeight' => 2,
                                          'hvnRegionId'  => 4,
                                          'comments_per_page' => 10,
                                          'page_number' => 1
                                    ));
	}
	
	public function editAction()
	{
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$id = $this->_request->getParam("id");
    	if (!$n = $this->m->findByPrimary($id))
        {              
            $this->view->errorMessage .= t(305);
            $this->renderToHolder('common/error.phtml');
            return;
        }
        
		//check for permission here
		//check rights
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage .= t(306);
            $this->renderToHolder('common/error.phtml');
            return;
		}

		$uIdentity = $auth->getIdentity();
		//if not admin
		// or not owner
		if (($uIdentity->id != $n['poster_id'] && strpos ($sess->userPermissions, 'update event') === false) ||
			($uIdentity->id == $n['poster_id'] && strpos ($sess->userPermissions, 'update own event') === false))
		{
		 	$this->view->errorMessage .= t(306);
            $this->renderToHolder('common/error.phtml');
            return;
		}  
		
	
        //everything's fine. Continue editing
        $form = new Form_News();
        $form->cluBuild(array ('action' => 'edit', 'view' => $this->view, 'userPermissions' => $sess->userPermissions));
        
        //populate the data with 
		if(!$this->_request->isPost())
            $form->populate($this->m->transformToFormArray($n,true));
			
        else if ($form->isValid($_POST))
        {	
			$data = $this->_request->getParams();
        	$articleData = array();
            $articleData['article_title'] 		= $data['title'];
            $articleData['article_body']  		= $data['body'];
        	$articleData['article_keywords'] 	= $data['keywords'];
            $article_id = $data['article_id'];
            
            if (!($this->mArticle->saveRaw(null, $articleData, $article_id,false)))
            {
            	$this->view->errorMessage .= t(503);
            }
            if ($this->m->saveRaw($n, $data, $id, false))
            {
    		 	$this->view->successMessage .= t(307);
            }
            else 
                $this->view->errorMessage .= t(308);
        }
        else 
        	$this->view->errorMessage .= t(71);
        	
        $this->view->form = $form;
		$this->view->article_id = $n['article_id'];
        $this->view->id = $id;
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
        $this->renderToHolder('index/new.phtml', false, null, 4, 1);    
	}

	public function searchAction()
    {
    	$data = $this->_request->getParams();
//    	die_a($data);
      	$form = new Form_NewsSearch();
      	$form->cluBuild(array ('view' => $this->view, 'cluSearchMode' => 'simpleSearch'));
        $this->view->form = $form; 
		if($this->_request->isPost() && $form->isValid($_POST))
		{
	    	if($paginator = $this->m->search($data))
    		{
    			$paginator= $this->generatePaginator($paginator, 1, $data['news_per_page'], 3, 'Jumping');
                $form->populate($data);  
    			
        	}
			//cache in $_SESSION
           	$sess = new Zend_Session_Namespace("news_paginator");
            $sess->news_search_params = array("search_params" => $data); 
		}
        else if(!empty($data['page']) && $data['page'] != null){
			$sess = new Zend_Session_Namespace("news_paginator");
        	$data = $sess->news_search_params;
           	if(isset($data))
           	{
               $select = $this->m->search($data['search_params']);
               $paginator = $this->generatePaginator($select, $this->_getParam('page'), $data['search_params']['news_per_page'], 3, 'Jumping');
               //populate form
               $form->populate($data['search_params']);
           	}
        }

        if(isset($paginator))
       	{                
            $this->view->paginator = $paginator;
        	foreach($paginator->getCurrentItems() as $temp)
        	{
            	$tmp = $this->m->transformToFormArray($temp,false);
        		$List[] = $tmp;
        	}
            if (isset($List))
    			$this->view->newsList = $List;//list of found events
            $this->renderToHolder('index/list.phtml',false, null, 4,2); 
       	}
       	$this->view->lang = Zend_Registry::get('viewLang');
       	
       	$loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
        $this->renderToHolder('index/search.phtml',false, null, 4,1); //search box 
    }
    
	public function generatePaginator($select, $pageNumber, $itemsPerPage, $pageRange, $style)
    {
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
        $paginator->setItemCountPerPage($itemsPerPage);
        $paginator->setCurrentPageNumber($pageNumber);
        $paginator->setPageRange($pageRange);
        Zend_Paginator::setDefaultScrollingStyle($style);
        return $paginator;
    }
    
	public function successAction()
    {
         $this->view->commentId =  $this->_request->getParam("lastInsertId");
         $this->renderToHolder( 'common/success.phtml');  
    }
    
    public function galleryAction()
    {
        $newId = $this->_request->getParam("id");
        $auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
        if (!$p = $this->m->findByPrimary($newId, true))
        {
        	$this->view->errorMessage .= t(213);
            $this->renderToHolder( 'common/error.phtml');
            return;
        }
        $this->view->id = $newId;
        if(!empty($uIdentity))
        	$this->view->uid = $uIdentity->id;
        
        $loginRequest = array(
                                'module' => 'user',
                                'controller' => 'block',
                                'action' => 'login',
                                'regionId' => 1,
                                'boxWeight' => 1,
								'theme' => 'second'
                );
		$this->addMiniAction($loginRequest);
		
		$OnlineSupportRequest = array(
				'module' => 'hvn',
				'controller' => 'block',
				'action' => 'onlineSupport',
				'regionId' => 5,
				'boxWeight' => 2,
		);
		$this->addMiniAction($OnlineSupportRequest);
		
		$infoSupportRequest = array(
				'module' => 'common',
				'controller' => 'block',
				'action' => 'infoSupport',
				'regionId' => 5,
				'boxWeight' => 3,
		);
		$this->addMiniAction($infoSupportRequest);
		
		$mapRequest = array(
                            'module' => 'hvn',
                            'controller' => 'block',
                            'action' => 'mapVietnam',
                            'regionId' => 6,
                            'boxWeight' => 1,
                );
		$this->addMiniAction($mapRequest);
		
        $this->renderToHolder( 'index/gallery.phtml', false, null, 4, 2);                 
    }
}
?>
